package com.cennavi.controller;

import com.cennavi.filter.Myfilter;
import com.cennavi.function.KpiFunction;
import com.cennavi.function.ListSumFunction;
import com.cennavi.function.MinFunction;
import com.cennavi.ruleList.Message;
import com.cennavi.ruleList.Refuse;
import com.googlecode.aviator.AviatorEvaluator;
import org.kie.api.KieServices;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.rule.AgendaFilter;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.KnowledgeBaseFactory;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderError;
import org.kie.internal.builder.KnowledgeBuilderErrors;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lixiaoshuang on 2018/9/21.
 */
@Controller
@RequestMapping("/my")
public class test {
    @RequestMapping("/test")
    public @ResponseBody Object mytest(){

        //从工厂中获得KieServices实例
        KieServices kieServices = KieServices.Factory.get();
        //从KieServices中获得KieContainer实例，其会加载kmodule.xml文件并load规则文件
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        //建立KieSession到规则文件的通信管道
        KieSession kSession = kieContainer.newKieSession("ksession-rules");
        Message message = new Message();
        message.setMessage("rules");
        message.setStatus(Message.HELLO);
        //将实体类插入执行规则
        kSession.insert(message);
//        kSession.fireAllRules();
//        AgendaFilter filter = new Myfilter("Hello World");
//        kSession.fireAllRules(filter);
//        int count=kSession.fireAllRules(filter);
        AgendaFilter filter = new Myfilter("GoodBye");
//        kSession.fireAllRules(filter);
        int count=kSession.fireAllRules(filter);
        System.out.println("规则执行条数：--------"+count);
        System.out.println("规则执行完成--------"+message.toString());
        kSession.destroy();
        return "over";
//        System.out.println(kSession.getGlobals().toString());
    }
    @RequestMapping("/test2")
    public @ResponseBody Object mytest2(){

//        try {
//            Map<String,String> refuseDate=new HashMap<String, String>();
//            KieServices ks = KieServices.Factory.get();
//            KieContainer kContainer = ks.getKieClasspathContainer();
//            KieSession kSession = kContainer.newKieSession("ksession-rules");
//            Refuse refuse=new Refuse();
//            refuse.setAge(34);
////            kSession.setGlobal("rules",refuseDate);
//            kSession.insert(refuse);
////            kSession.execute()
//            int count=kSession.fireAllRules();
//            System.out.println("规则执行条数：--------"+count);
//            System.out.println("规则执行完成--------"+refuse.toString());
//            System.out.println(kSession.getGlobals().toString());
//        } catch (Throwable t) {
//            t.printStackTrace();
//        }
        return "结束";

    }
    @RequestMapping("/test3")
    public void mytest3(){

        try {
            Map<String,String> refuseDate=new HashMap<String, String>();
            KieServices ks = KieServices.Factory.get();
            KieContainer kContainer = ks.getKieClasspathContainer();
            StatelessKieSession kSession = kContainer.newStatelessKieSession("ksession-rules");
            Refuse refuse=new Refuse();
            refuse.setAge(34);
            kSession.setGlobal("refuseDate",refuseDate);
            kSession.execute(refuse);
//            kSession.
//            int count=kSession.gete();
//            System.out.println("规则执行条数：--------"+count);
            System.out.println("规则执行完成--------"+refuse.toString());
            System.out.println(kSession.getGlobals().toString());
        } catch (Throwable t) {
            t.printStackTrace();
        }

    }
    @RequestMapping("/test4")
    public void mytest4(){
        String rule = "package com.cennavi.ruleList\r\n";
        rule += "import com.cennavi.ruleList.Message;\r\n";
        rule += "rule \"rule1\"\r\n";
        rule += "\twhen\r\n";
        rule += "Message( status == 1, myMessage : message )";
        rule += "\tthen\r\n";
        rule += "\t\tSystem.out.println( 1+\":\"+myMessage );\r\n";
        rule += "end\r\n";


        String rule2 = "package com.cennavi.ruleList\r\n";
        rule += "import com.cennavi.ruleList.Message;\r\n";

        rule += "rule \"rule2\"\r\n";
        rule += "\twhen\r\n";
        rule += "Message( status == 2, myMessage : message )";
        rule += "\tthen\r\n";
        rule += "\t\tSystem.out.println( 2+\":\"+myMessage );\r\n";
        rule += "end\r\n";


        StatefulKnowledgeSession kSession = null;
        try {


            KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder();
            //装入规则，可以装入多个
            kb.add(ResourceFactory.newByteArrayResource(rule.getBytes("utf-8")), ResourceType.DRL);
            kb.add(ResourceFactory.newByteArrayResource(rule2.getBytes("utf-8")), ResourceType.DRL);

            KnowledgeBuilderErrors errors = kb.getErrors();
            for (KnowledgeBuilderError error : errors) {
                System.out.println(error);
            }
            KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
            kBase.addKnowledgePackages(kb.getKnowledgePackages());

            kSession = kBase.newStatefulKnowledgeSession();


            Message message1 = new Message();
            message1.setStatus(1);
            message1.setMessage("hello world!");

            Message message2 = new Message();
            message2.setStatus(2);
            message2.setMessage("hi world!");

            kSession.insert(message1);
            kSession.insert(message2);
            int count=kSession.fireAllRules();
            System.out.print("运行了"+count+"回");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            if (kSession != null)
                kSession.dispose();
        }


    }


    @RequestMapping("/test5")
    public @ResponseBody Object mytest5(){
        Map<String, Object> env = new HashMap<String, Object>();
        List list = new ArrayList();
        list.add(10.0);
        list.add(20.0);
        list.add(20.34);
//        list.add(45.76);
        env.put("list",list);

        AviatorEvaluator.addFunction(new ListSumFunction());
        AviatorEvaluator.addFunction(new KpiFunction());
        Object result = AviatorEvaluator.execute("listsum(list)", env);
        Map<String, Object> env1 = new HashMap<String, Object>();
        List list1 = new ArrayList();
        list1.add(1.0);
        list1.add(2.0);
        list1.add(2.34);
        env1.put("list",list);
        Object result1 = AviatorEvaluator.execute("listsum(list)", env1);
        System.out.println(result);
        Map<String, Object> env3 = new HashMap<String, Object>();
        env3.put("wt",0.6);
        env3.put("a",Double.parseDouble(result.toString()));
        env3.put("b",Double.parseDouble(result.toString()));
        env3.put("size",list1.size()+list.size());
        Object result3 = AviatorEvaluator.execute("kpi(((wt*a+(1-wt)*b))/size)", env3);
        return result3;


    }


}
